package com.wpzf.zxhc.utils;

import org.apache.pdfbox.multipdf.PDFMergerUtility;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPage;
import org.apache.pdfbox.pdmodel.PDPageContentStream;
import org.apache.pdfbox.pdmodel.graphics.image.PDImageXObject;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

public class PdfUnits {

    public static void addDocxToPDF(PDDocument doc, String docxPath, String pdfPath) throws Exception {
        WordUnits.wordToPdf(docxPath, pdfPath);
        appendPDF(doc, pdfPath);
    }

    public static void appendPDF(PDDocument doc, String pdfPath) throws IOException {
        // 读取要附加的PDF文件
        PDDocument srcDoc = PDDocument.load(new File(pdfPath));
        // 将源文档的所有页面合并到目标文档中
        PDFMergerUtility merger = new PDFMergerUtility();
        merger.appendDocument(doc, srcDoc);
        // 关闭源文档
        srcDoc.close();
    }

    public static void addImageToPDF(PDDocument doc, String imagePath) throws IOException {
        PDPage page = new PDPage();
        doc.addPage(page);

        // 加载图片
        BufferedImage bimg = ImageIO.read(new File(imagePath));
        PDImageXObject pdImage = PDImageXObject.createFromFile(imagePath, doc);

        // 获取图片和页面的尺寸
        float imageWidth = pdImage.getWidth();
        float imageHeight = pdImage.getHeight();
        float pageWidth = page.getMediaBox().getWidth();
        float pageHeight = page.getMediaBox().getHeight();

        // 计算缩放比例，保持图片比例不变
        float scale = Math.min(pageWidth / imageWidth, pageHeight / imageHeight);

        // 设置最大宽度
        float scaledWidth = imageWidth * scale;
        float scaledHeight = imageHeight * scale;

        // 在页面中心放置图片
        float xPosition = (pageWidth - scaledWidth) / 2;
        float yPosition = (pageHeight - scaledHeight) / 2;

        PDPageContentStream contentStream = new PDPageContentStream(doc, page);
        contentStream.drawImage(pdImage, xPosition, yPosition, scaledWidth, scaledHeight);
        contentStream.close();
    }

}
